#include<iostream>

// 给二维数组分配内存
template <class T>
bool make2dArray(T**& x, int numberOfRows, int numberOfColumns)
{
    try {
        x = new T * [numberOfRows]; // x 指针数组
        for (int i = 0;i < numberOfRows;i++)
            x[i] = new T[numberOfColumns];
        return true;
    }
    catch (std::bad_alloc e) {
        std::cerr << "Memory allocation failed: " << e.what() << std::endl;
        return false;
    }
}

// 释放二维数组内存
template <class T>
void delete2dArray(T**& x, int numberOfRows)
{
    for (int i = 0;i < numberOfRows;i++) {
        delete[] x[i];
    }
    delete[] x;
    x = nullptr;
}

int main()
{
    // using std::cout, std::endl;
    // new : int* y = new int(5);
    int* y;
    y = new int;
    *y = 5;
    std::cout << *y << std::endl;

    // 一维数组
    int n;
    float* arr;
    try {
        arr = new float[n];
    }
    catch (std::bad_alloc e) {
        std::cerr << "Memory allocation failed: " << e.what() << std::endl;
        // std::cout << "Memory allocation failed: " << e.what() << std::endl;
        exit(1);
    }

    // delete
    delete y;
    delete[] arr;

    // 二维数组
    n = 5;
    int(*arr2)[5];
    arr2 = new int[n][5];
    for (int i = 0; i < n; i++)
        for (int j = 0; j < 5; j++)
            arr2[i][j] = i * 5 + j;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < 5; j++)
            std::cout << arr2[i][j] << " ";
        std::cout << std::endl;
    }
    std::cout << arr2 << std::endl;
    std::cout << arr2[0] << std::endl;
    std::cout << arr2[1] << std::endl;

    // int * arr[5] 与  int(*arr)[5] 不同
    int (*arr3)[5];
    try {
        arr3 = new int[n][5];
    }
    catch (std::bad_alloc e) {
        std::cerr << "Memory allocation failed: " << e.what() << std::endl;
        exit(1);
    }

    delete[] arr2;
    delete[] arr3;

    // 二维数组
    int** arr4;
    int rows = 3, cols = 5;
    bool temp = make2dArray(arr4, rows, cols);
    std::cout << temp << std::endl;
    delete2dArray(arr4, rows);

    return 0;
}